using Dapper;
using Eno.Domain.Entity.App;
using Eno.Domain.Repositories;
using Npgsql;

namespace Eno.Infrastructure.InfRepositories;

public class RoleRepository : IRepository<AppRole>
{

    public readonly string _connectionString;

    public RoleRepository(string connectionString)
    {
        _connectionString = connectionString;
    }

    public async Task<int> AdditionRoleAsync(AppRole entity)
    {
        entity.ID = Guid.NewGuid();
        using var conn = new NpgsqlConnection(_connectionString);
        var number = await conn.ExecuteAsync("insert into app_roles(\"ID\",\"RoleName\",\"DataRange\",\"IsActived\",\"IsDeleted\",\"CreatedAt\",\"UpdatedAt\") values(@ID,@RoleName,@DataRange,@IsActived,@IsDeleted,@CreatedAt,@UpdatedAt)", entity);
        return number;
    }

    public async Task<int> DeleteRoleAsync(Guid guid)
    {
        using var conn = new NpgsqlConnection(_connectionString);
        var number = await conn.ExecuteAsync("delete  from app_roles where \"ID\"=@ID ", new { ID = guid });
        return number;
    }


    public async Task<AppRole?> GetRoleByNameAsync(string roleName)
    {
        using var conn = new NpgsqlConnection(_connectionString);
        var role = await conn.QueryFirstOrDefaultAsync<AppRole>("select * from app_roles where \"RoleName\"=@RoleName", new { RoleName = roleName });
        return role;

    }

    public async Task<AppRole?> GetRoleByIdAsync(Guid guid)
    {
        using var conn = new NpgsqlConnection(_connectionString);
        var role = await conn.QueryFirstOrDefaultAsync<AppRole>("select * from app_roles where \"ID\"=@ID", new { ID = guid });
        return role;
    }

    public async Task<int> UpdateRoleAsync(AppRole entity)
    {
        using var conn = new NpgsqlConnection(_connectionString);
        var number = await conn.ExecuteAsync("update app_roles set \"RoleName\"=@RoleName,\"DataRange\"=@DataRange,\"IsActived\"=@IsActived,\"Remarks\"=@Remarks where \"ID\"=@ID", entity);
        return number;
    }

    public async Task<IEnumerable<AppRole>> GetRoleAllAsync()
    {
        using var conn = new NpgsqlConnection(_connectionString);
        return await conn.QueryAsync<AppRole>("select * from app_roles");
    }
}